package com.wyp168.leetcode.treenode;

import com.wyp168.leetcode.ThreeSum;
import com.wyp168.leetcode.listnode.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName PreorderTraversal
 * @Description 返回二叉树的前序遍历（根-左-右）
 * @Author wyp168
 * @Date 2022/7/20 08:36
 */
public class PreorderTraversal {
    public static void main(String[] args) {
        TreeNode root = new TreeNode();
        root.setVal(1);
        root.setLeft(null);

        TreeNode rightNode = new TreeNode();
        rightNode.setVal(2);
        rightNode.setLeft(new TreeNode((3)));

        root.setRight(rightNode);

        System.out.println(preorderTraversal(null));


    }

    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return new ArrayList<Integer>();
        }
        recurrenceMethod(root,res);
        return res;
    }

    /**
     * 递归遍历并封装到res集合中（前序遍历）
     */
    public static void recurrenceMethod(TreeNode root, List<Integer> res) {
            res.add(root.val);

        if (root.left != null) {
            recurrenceMethod(root.left,res);
        }

        if (root.right != null) {
            recurrenceMethod(root.right,res);
        }
    }
}
